package com.winning.dps.ds.service.common.impl;


import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.excel.util.FileUtils;
import com.baomidou.mybatisplus.core.toolkit.IOUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.winning.dps.ds.service.common.CommonApiService;
import com.winning.dps.ds.service.common.MessageService;
import common.entity.SysUserEntity;
import common.util.Base64;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPOutputStream;

/**
 * @desc:
 * @auther: shipengfei
 * @date: 2021/2/3 20:28
 **/
@Slf4j
@Service
public class MessageServiceImpl implements MessageService {

    private final static String sendMsgUpi = "/v1.0/services/message/send";
    private final static String getTokenUrl = "/v1.0/services/permissions/getToken";

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private CommonApiService commonApiService;


    @Value("${moudle}")
    private String moudle;


    /**
     * 消息发送
     *
     * @param templateCode 模板编码
     * @param msgTitle     消息标题
     * @param sync         同步、异步
     * @param param        调用参数
     */
    @Override
    public void sendMessage(String templateCode, String msgTitle, boolean sync, Map<String, String> param) {
        Map<String, Object> params = new HashMap<>();
        params.put("mbbm", templateCode);
        params.put("xxzt", msgTitle);
        params.put("dyxt", "DQMS");
        params.put("fsfs", sync ? "SYNC" : "ASYNC");
        params.put("dycs", param);

        String jcfwurl = commonApiService.queryQjcs("jcfwServiceUrl").getCsz() + sendMsgUpi;

        String token = this.getJcfwToken();
        Map<String, String> headers = new HashMap<>();
        headers.put("token", token);

        this.doPost(jcfwurl, headers, params);
    }

    /**
     * 获取基础服务token
     *
     * @return
     */
    @Override
    public String getJcfwToken() {
        Map param = Maps.newHashMap();
        param.put("username", "platAdmin");
        SysUserEntity sysUserEntity = commonApiService.queryByUserName("platAdmin");
        if (sysUserEntity == null) {
            throw new RuntimeException("当前用户不存在");
        }
        param.put("password", sysUserEntity.getDlmm());

        String jcfwurl = commonApiService.queryQjcs("jcfwServiceUrl").getCsz() + getTokenUrl;
        Map resMap = (Map) this.doPost(jcfwurl, Maps.newHashMap(), param);

        return resMap != null ? resMap.get("token") + "" : "";
    }

    public static byte[] compress(byte[] data) {
        GZIPOutputStream gzip = null;
        ByteArrayOutputStream baos = null;
        byte[] newData = null;

        try {
            baos = new ByteArrayOutputStream();
            gzip = new GZIPOutputStream(baos);

            gzip.write(data);
            gzip.finish();
            gzip.flush();


            newData = baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(gzip);
            IOUtils.closeQuietly(baos);
        }

        return newData;
    }


    /**
     * 邮件发送质控报告
     * @param param 调用参数
     * @param filePath 报告路径
     */
    @Override
    public void sendZkbg(Map<String, Object> param, String filePath, Map<String, Object> dycs) throws IOException {
        File file = new File(filePath);
        byte[] fileContent = FileUtils.readFileToByteArray(file);
        String base64 = Base64.encodeBytes(compress(fileContent));

        Map<String, Object> params = Maps.newHashMap();
        params.put("mbbm", "DQMS_PTYW_PFJK_EMAIL"); //需新增邮件模板
        params.put("xxzt", "质控报告（" + param.get("day") + "）");
        params.put("dyxt", "DQMS");
        params.put("fsfs", "SYNC");
        params.put("dycs", dycs);

        ArrayList<Map<String,String>> attachs = Lists.newArrayList();
        Map<String, String> attach = Maps.newHashMap();
        attach.put("filename","质控报告（"+ param.get("day") + "）.pdf");
        attach.put("filebytes", base64);
        attachs.add(attach);
        params.put("attachments", attachs);



        String jcfwurl = commonApiService.queryQjcs("jcfwServiceUrl").getCsz() + sendMsgUpi;

        String token = this.getJcfwToken();
        Map<String, String> headers = new HashMap<>();
        headers.put("token", token);

        this.doPost(jcfwurl, headers, params);
    }

    /**
     * @param url
     * @param params
     * @return
     */
    private Object doPost(String url, Map<String, String> headers, Map<String, Object> params) {
        Object res = null;
        try {
            if("1".equalsIgnoreCase(moudle)) {

            }else {
                HttpHeaders requestHeaders = new HttpHeaders();
                requestHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
                for (String key : headers.keySet()) {
                    requestHeaders.add(key, headers.get(key));
                }
                HttpEntity<Map> requestEntity = new HttpEntity<>(params, requestHeaders);
                Map resMap = restTemplate.postForObject(url, requestEntity, Map.class);
                log.info("请求url：{}，参数：{}，结果：{}", url, params, JSONUtils.toJSONString(resMap));
                if ("200".equals(resMap.get("statuscode") + "")) {
                    res = resMap.get("repData");
                }
            }


        } catch (Exception e) {
            log.error("请求url:" + url + ",失败：" + e);
        }
        return res;
    }


}
